package com.lhz.framework.manager.threadManager;

import com.lhz.CustomizeApplicationContext;
import com.lhz.common.utils.ip.AddressUtils;
import com.lhz.common.utils.ip.IpUtils;
import com.lhz.framework.manager.threadManager.factory.AsyncBean;
import com.lhz.project.system.model.entity.auth.LoginInfo;
import com.lhz.project.system.model.entity.base.LoginLog;
import com.lhz.project.system.service.base.LogService;
import eu.bitwalker.useragentutils.UserAgent;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Scope;

/**
 * spring 多例
 *
 * @author LiGezZ
 */
@Scope("prototype")
public class LoginLogThreadManager extends BaseThreadManager {

    public LoginLogThreadManager(AsyncBean asyncBean, Object obj) {
        super(asyncBean, obj);
    }

    @Override
    public void run() {

        HttpServletRequest request = (HttpServletRequest) this.obj;
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(request);
        if (ip == null) {
            ip = "127.0.0.1";
        }
        String address = AddressUtils.getRealAddressByIp(ip);
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();

        //出线程中获取业务信息
        LoginInfo loginInfo = (LoginInfo) asyncBean.getObject();
        String username = loginInfo.getUsername();
        String message = loginInfo.getMessage();
        Integer status = loginInfo.getStatus();
        String id = loginInfo.getLogId();

        // 封装对象
        LoginLog loginLog = new LoginLog();
        loginLog.setId(id);
        loginLog.setUserName(username);
        loginLog.setIp(ip);
        loginLog.setLocation(address);
        loginLog.setBrowser(browser);
        loginLog.setOs(os);
        loginLog.setMsg(message);
        // 日志状态
        loginLog.setStatus(status);

        // 插入数据
        CustomizeApplicationContext.getBean(LogService.class).insertLoginLog(loginLog);
    }

    private static String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg + "]";
    }
}
